<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { fetchDealerGoodsStoreList } from '@/api/goods'
import logger from '@/utils/logger'
import { formatDateTime } from '@/utils/dayjs'

// 使用defineModel替代props和emit
const selectedGoods = defineModel('selectedGoods', {
  type: Array,
  default: () => [],
})
// 定义关闭事件
const emit = defineEmits(['close', 'confirm'])

// 表格引用，用于控制选中状态
const tableRef = ref(null)

const loading = ref(false)

// 查询条件
const requestData = ref({
  currentPage: 1,
  pageSize: 10,
  queryFields: {
    goodsName: '',
  },
})

const tableData = ref([])
const total = ref(0)

// 获取商品库存列表
const fetchStoreData = async () => {
  try {
    loading.value = true
    const params = {
      currentPage: requestData.value.currentPage,
      pageSize: requestData.value.pageSize,
      queryFields: {
        goodsName: requestData.value.queryFields.goodsName.trim() || null,
      },
    }
    const res = await fetchDealerGoodsStoreList(params)
    if (res.success && res.data) {
      tableData.value = res.data.list || []
      total.value = res.data.total || 0

      // 在表格数据更新后应用选中状态
      nextTick(() => {
        syncTableSelection()
      })
    } else {
      tableData.value = []
      total.value = 0
      ElMessage.error(res.msg || '获取库存列表失败')
    }
  } catch (error) {
    logger.error('获取库存列表失败', error)
    ElMessage.error('获取库存列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  requestData.value.currentPage = 1
  fetchStoreData()
}

// 重置搜索条件
const resetSearch = () => {
  requestData.value.queryFields.goodsName = ''
  requestData.value.currentPage = 1
  fetchStoreData()
}

// 处理分页变化
const handleSizeChange = (val) => {
  requestData.value.pageSize = val
  requestData.value.currentPage = 1
  fetchStoreData()
}

const handleCurrentChange = (val) => {
  requestData.value.currentPage = val
  fetchStoreData()
}

// 处理选择变更
const handleSelectionChange = (selection) => {
  // `selection` 参数仅包含当前页的选中行
  // 为了让 `reserve-selection` 在分页时正常工作，需要手动合并所有页面的选中项

  // 1. 获取当前页所有行的 ID
  const currentPageIds = new Set(tableData.value.map((item) => item.dealerGoodsStoreId))
  // 2. 从已选列表中，筛选出不属于当前页的选中项（即其他页面的选中项）
  const otherPageSelection = selectedGoods.value.filter(
    (item) => !currentPageIds.has(item.dealerGoodsStoreId),
  )
  // 3. 将其他页面的选中项与当前页的选中项合并，更新 v-model
  selectedGoods.value = [...otherPageSelection, ...selection]
}

// 应用已选商品到表格
const syncTableSelection = () => {
  if (!tableRef.value) return
  // 1. 清除表格当前所有勾选，避免状态残留
  tableRef.value.clearSelection()

  // 2. 如果外部传入了已选商品，则在当前页进行回显
  if (Array.isArray(selectedGoods.value) && selectedGoods.value.length > 0) {
    const selectedIds = new Set(selectedGoods.value.map((item) => item.dealerGoodsStoreId))
    tableData.value.forEach((row) => {
      if (selectedIds.has(row.dealerGoodsStoreId)) {
        tableRef.value.toggleRowSelection(row, true)
      }
    })
  }
}

// 关闭选择器
const closeSelector = () => {
  selectedGoods.value = []
  emit('close')
}

/**
 * @description 确认添加
 */
const handleConfirm = () => {
  if (!selectedGoods.value || selectedGoods.value.length === 0) {
    ElMessage.warning('请至少选择一个商品')
    return
  }
  emit('confirm')
}

onMounted(() => {
  fetchStoreData()
})
</script>

<template>
  <div class="goods-selector">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :inline="true" :model="requestData.queryFields">
        <el-form-item label="商品名称">
          <el-input
            v-model="requestData.queryFields.goodsName"
            placeholder="请输入商品名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><LineMdSearch /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <template #icon>
              <el-icon><LineMdSearch /></el-icon>
            </template>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <template #icon>
              <el-icon><LineMdClose /></el-icon>
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-wrapper">
      <el-table
        ref="tableRef"
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        row-key="dealerGoodsStoreId"
        reserve-selection
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="商品图片" width="100" align="center">
          <template #default="{ row }">
            <el-image
              v-if="row.goodsPicture"
              :src="row.goodsPicture"
              style="width: 50px; height: 50px; border-radius: 4px"
              :preview-src-list="[row.goodsPicture]"
              fit="cover"
              preview-teleported
            />
            <div v-else class="no-image">无图片</div>
          </template>
        </el-table-column>
        <el-table-column label="商品名称" prop="goodsName" min-width="120" align="center" />
        <el-table-column label="有效期" min-width="200" align="center">
          <template #default="{ row }">
            {{ formatDateTime(row.periodStartingDate, 'YYYY-MM-DD') }} 至
            {{ formatDateTime(row.periodEndDate, 'YYYY-MM-DD') }}
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="库存" width="100" align="center" />
        <el-table-column prop="points" label-width="200" label="原价格（元）" align="center">
          <template #default="{ row }">
            <el-tag type="success">
              {{ row.points }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="requestData.currentPage"
          v-model:page-size="requestData.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <div class="action-container">
      <el-button @click="closeSelector">
        <template #icon>
          <el-icon><LineMdClose /></el-icon>
        </template>
        关 闭
      </el-button>
      <el-button type="primary" @click="handleConfirm">
        <template #icon>
          <el-icon><LineMdPlus /></el-icon>
        </template>
        确定
      </el-button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.goods-selector {
  display: flex;
  flex-direction: column;
  height: 100%;
  height: calc(100vh - 200px);
  gap: 5px;

  .search-container {
    border: 1px solid #ebeef5;
    border-radius: 10px;
    padding: 15px 15px 0;
    background-color: #fff;
  }

  .table-wrapper {
    flex: 1;
    overflow: auto;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    gap: 10px;
    background-color: #fff;
    padding: 15px;
    border-radius: 10px;

    .pagination-container {
      display: flex;
      justify-content: center;
      margin-top: 10px;
    }
  }

  .action-container {
    display: flex;
    justify-content: flex-end;
    background-color: #fff;
    border-radius: 10px;
  }

  .no-image {
    width: 50px;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #909399;
    background-color: #f5f7fa;
    font-size: 12px;
    border-radius: 4px;
    border: 1px dashed #d9d9d9;
  }
}
</style>
